package com.ncloud.auth.util;

import java.util.Date;
import java.util.Map;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;

import com.ncloud.auth.config.Constant;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JWT {
	@Value("${spring.profiles.active}")
    private static String profiles;
		
	public static SecretKey generalKey(){
		String stringKey = profiles + Constant.jwt_secret;
		byte[] encodedKey = Base64.decodeBase64(stringKey);
		SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
		return key;
	}
	public static String createJWT(String id, String subject, long ttlMillis, Map<String, Object> claims){
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);
		SecretKey key = generalKey();
		JwtBuilder builder = Jwts.builder()
			.setId(id)
			.setIssuedAt(now)
			.setSubject(subject)
		    .signWith(signatureAlgorithm, key);
		if(claims != null && !claims.isEmpty()) {
			builder.setClaims(claims);
		}
		if (ttlMillis >= 0) {
		    long expMillis = nowMillis + ttlMillis * 1000;
		    Date exp = new Date(expMillis);
		    builder.setExpiration(exp);
		}
		return builder.compact();
	}

	public static Claims parseJWT(String jwt){
		SecretKey key = generalKey();
		Claims claims = Jwts.parser()      
		   .setSigningKey(key).setAllowedClockSkewSeconds(3600 * 24)
		   .parseClaimsJws(jwt).getBody();
		return claims;

	}
}
